<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :before-close="handleClose"
    :title="title"
    width="600px"
  >
    <el-alert
      :closable="false"
      :style="{marginBottom: '20px'}"
      show-icon
      title="提示: 客户代码、产品型号、工艺规范编号、工序号和封装形式至少填写一个"
      type="info"/>
    <!-- <dynForm
      ref="topForm"
      :form-disable="formTopDisable"
      :info-form="searchForm"
      :rules="rules"
      :search-tags="searchTopTags"
      :is-inline="false"
      :select-list="selectList"
    /> -->
    <el-form
      :rules="rules"
      :disabled="formTopDisable"
      :model="searchForm"
      label-width="120px">
      <el-form-item :label="this.$t('customer')">
        <el-input v-model="searchForm.custCode" :placeholder="`${$t('pleaseInput')}${$t('customer')}`" clearable/>
      </el-form-item>
      <el-form-item :label="this.$t('productName')">
        <el-input v-model="searchForm.productType" :placeholder="`${$t('pleaseInput')}${$t('productName')}`" clearable/>
      </el-form-item>
      <el-form-item :label="this.$t('packageType')">
        <el-select
          v-model="searchForm.packageType"
          :placeholder="`${$t('pleaseSelect')}${$t('packageType')}`"
          clearable
          filterable
          allow-create
          default-first-option
          @change="addpackageTypeList"
        >
          <el-option
            v-for="item in packaingCodeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item :label="this.$t('processSpecificationNumber')">
        <el-input
          v-model="searchForm.processSpecificationNo"
          :placeholder="`${$t('pleaseInput')}${$t('processSpecificationNumber')}`"
          clearable/>
      </el-form-item>
      <el-form-item :label="this.$t('processNo')">
        <el-input v-model="searchForm.processFlow" :placeholder="`${$t('pleaseInput')}${$t('processNo')}`" clearable/>
      </el-form-item>
      <el-form-item :label="this.$t('userBatchNumber')">
        <el-input v-model="searchForm.custLotId" :placeholder="`${$t('pleaseInput')}${$t('userBatchNumber')}`" clearable/>
      </el-form-item>
    </el-form>
    <dynForm
      ref="dataForm"
      :form-disable="formDisable"
      :info-form="searchForm"
      :rules="rules"
      :search-tags="searchTags"
      :is-inline="false"
      :select-list="selectList"
    >
      <div :style="{display: 'flex'}">
        <el-form-item :label="$t('retrospectiveTimeLimit')" prop="limitTime">
          <div class="input-append">
            <el-input
              v-model="searchForm.limitTime"
              :placeholder="`${$t('pleaseInput')}${$t('retrospectiveTimeLimit')}`"
              :style="{ width: '200px' }"
            />
            <span />
          </div>
        </el-form-item>
        <el-form-item prop="limitUnit" label-width="0">
          <el-select v-model="searchForm.limitUnit" :style="{ width: '200px' }" disabled>
            <!-- v-for="item in limitUnitList" -->
            <el-option
              v-for="item in [{id: 3, name: 'EnumTimeUnit_Day'}]"
              :key="item.id"
              :label="$t(item.name)"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </div>
    </dynForm>
    <span slot="footer">
      <el-button icon="el-icon-circle-close" @click="handleClose">{{
        $t("cancel")
      }}</el-button>
      <el-button
        v-btnThrottle="doSave"
        type="primary"
        icon="el-icon-receiving"
      >{{ $t("save") }}</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import {
  getInfo,
  doAdd,
  doUpdate,
  getPackageTypeList
} from '@/api/auto-analyze-warning/defineVariation'
import { getAttributeDescList } from '@/api/system/attributes'
import { getEnumList } from '@/api/public'
export default {
  name: 'DefineModel',
  data() {
    const validateLimitTime = (rule, value, callback) => {
      if (!value || value < 1) {
        callback(new Error('追溯时间应大于等于1'))
      } else {
        callback()
      }
    }

    const validateLimitUnit = (rule, value, callback) => {
      if (!value) {
        callback(new Error(`${this.$t('pleaseSelect')}频率`))
      } else {
        callback()
      }
    }

    return {
      title: '',
      dialogVisible: false,
      searchForm: {
        limitUnit: 3
      },
      packaingCodeList: [],
      formDisable: false,
      formTopDisable: false,
      searchTopTags: [
        { label: this.$t('customer'), prop: 'custCode', tag: 'DynInput' },
        { label: this.$t('productName'), prop: 'productType', tag: 'DynInput' },
        {
          label: this.$t('packageType'),
          prop: 'packageType',
          tag: 'DynSelect'
        },
        {
          label: this.$t('processSpecificationNumber'),
          prop: 'processSpecificationNo',
          tag: 'DynInput'
        },
        { label: this.$t('processNo'), prop: 'processFlow', tag: 'DynInput' },
        {
          label: this.$t('userBatchNumber'),
          prop: 'custLotId',
          tag: 'DynInput'
        }
      ],
      searchTags: [
        {
          label: this.$t('ruleSelection'),
          prop: 'ruleIds',
          tag: 'DynSelect',
          multiple: true
        }
      ],
      selectList: {},
      limitUnitList: [],
      rules: {
        ruleIds: [
          {
            required: true,
            message: `${this.$t('pleaseSelect')}${this.$t('ruleSelection')}`,
            trigger: 'change'
          }
        ],
        limitTime: [
          {
            required: true,
            validator: validateLimitTime,
            trigger: 'blur'
          }
        ],
        limitUnit: [
          {
            required: true,
            validator: validateLimitUnit,
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    doSave() {
      this.$refs['dataForm'].$refs['dynForm'].validate((valid) => {
        if (valid) {
          if (this.searchForm.id) {
            doUpdate(this.$clearNull(this.searchForm)).then((res) => {
              this.$betterTips(res, this.handleUpdate, this.handleClose)
            })
          } else {
            doAdd(this.$clearNull(this.searchForm)).then((res) => {
              this.$betterTips(res, this.handleUpdate, this.handleClose)
            })
          }
        }
      })
    },
    async handleOpen(row, idEdit = false, disabled = false) {
      if (row && row.id) {
        const res = await getInfo({ id: row.id })
        this.searchForm = res.data
        if (disabled) {
          this.title = this.$t('details')
        } else {
          this.title = this.$t('modify')
        }
        if (idEdit) this.formTopDisable = true
      } else {
        this.title = this.$t('add')
      }
      this.formDisable = disabled
      this.dialogVisible = true
      this.getPackageTypes()
      this.getAttributeDescs()
      this.getEnumList()
      this.$nextTick(() => {
        this.$refs['dataForm'].$refs['dynForm'].clearValidate()
      })
    },
    addpackageTypeList(value) {
      const find = this.packaingCodeList.map(c => c.id).some(v => v === value)
      if (!find) {
        this.packaingCodeList.unshift({ id: value, name: value })
      }
    },
    handleClose() {
      Object.assign(this.$data, this.$options.data.call(this))
    },
    // 触发父组件更新
    handleUpdate() {
      this.$emit('initList')
    },
    // 获取z规则
    async getAttributeDescs() {
      const res = await getAttributeDescList({ names: 'INCREASE,DECREASE' })
      this.$set(this.selectList, 'ruleIds', res.data)
    },
    // 获取时间限制
    async getEnumList() {
      const res = await getEnumList({ enumName: 'EnumTimeUnit', showType: 1 })
      this.limitUnitList = res.data
    },
    async getPackageTypes() {
      const res = await getPackageTypeList()
      // this.$set(this.selectList, 'packageType', res.data)
      this.packaingCodeList = res.data
    }
  }
}
</script>

<style scoped lang="scss">
.input-append {
  display: flex;
  span {
    padding: 0 10px;
  }
}
::v-deep .el-select {
  width: 100%;
}
</style>
